package com.gc.materialdesign.views;

import com.gc.materialdesign.utils.ShapeUtil;
import com.gc.materialdesign.utils.Utils;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Texture;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

public abstract class Button extends CustomView
        implements Component.TouchEventListener, Component.FocusChangedListener {
    // Complete in child class
    int minWidth;
    int minHeight;
    int background;
    float rippleSpeed = 12f;
    int rippleSize = 3;
    String rippleColor;
    ClickedListener onClickListener;
    boolean clickAfterRipple = true;
    String backgroundColor = "#1E88E5FF";
    private Text textButton;
    Context context;

    public Button(Context context) {
        this(context, null);
    }

    public Button(Context context, AttrSet attrs) {
        this(context, attrs, null);
    }

    public Button(Context context, AttrSet attrs, String defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        setDefaultProperties();
        boolean animateIsPresent = attrs.getAttr("animate").isPresent();
        if (animateIsPresent) {
            clickAfterRipple = attrs.getAttr("animate").get().getBoolValue();
        }
        setAttributes(attrs);
        beforeBackground = backgroundColor;
        if (rippleColor == null) {
            rippleColor = makePressColorString();
        }
        setTouchEventListener(this);
        setFocusChangedListener(this);
    }

    protected void setDefaultProperties() {
        // Min size
        setMinHeight(Utils.dpToPx(minHeight, context));
        setMinWidth(Utils.dpToPx(minWidth, context));
        // Background shape
        setBackgroundColor(backgroundColor);
    }

    // Set atributtes of XML to View
    protected abstract void setAttributes(AttrSet attrs);

    // ### RIPPLE EFFECT ###

    float x = -1, y = -1;
    float radius = -1;

    @Override
    public boolean onTouchEvent(Component component, TouchEvent event) {
        invalidate();
        MmiPoint mmiPoint = event.getPointerScreenPosition(event.getIndex());
        if (isEnabled()) {
            isLastTouch = true;
            if (event.getAction() == TouchEvent.PRIMARY_POINT_DOWN) {
                radius = getHeight() / rippleSize;
                x = Math.abs(mmiPoint.getX() - getLocationOnScreen()[0]);
                y = Math.abs(mmiPoint.getY() - getLocationOnScreen()[1]);
            } else if (event.getAction() == TouchEvent.POINT_MOVE) {
                radius = getHeight() / rippleSize;
                x = Math.abs(mmiPoint.getX() - getLocationOnScreen()[0]);
                y = Math.abs(mmiPoint.getY() - getLocationOnScreen()[1]);
                if (!(Math.abs(mmiPoint.getX() - getLocationOnScreen()[0]) <= getWidth()
                        && Math.abs(mmiPoint.getY() - getLocationOnScreen()[1]) <= getHeight())) {
                    isLastTouch = false;
                    x = -1;
                    y = -1;
                }
            } else if (event.getAction() == TouchEvent.PRIMARY_POINT_UP) {
                if (Math.abs(mmiPoint.getX() - getLocationOnScreen()[0]) <= getWidth()
                        && Math.abs(mmiPoint.getY() - getLocationOnScreen()[1]) <= getHeight()) {
                    radius++;
                    if (!clickAfterRipple && onClickListener != null) {
                        onClickListener.onClick(this);
                    }
                } else {
                    isLastTouch = false;
                    x = -1;
                    y = -1;
                }
            } else if (event.getAction() == TouchEvent.CANCEL) {
                isLastTouch = false;
                x = -1;
                y = -1;
            }
        }
        return true;
    }

    @Override
    public void onFocusChange(Component component, boolean gainFocus) {
        if (!gainFocus) {
            x = -1;
            y = -1;
        }
    }

    public PixelMap makeCircle() {
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
        initializationOptions.pixelFormat = PixelFormat.ARGB_8888;
        initializationOptions.size =
                new Size(getWidth() - Utils.dpToPx(6, context), getHeight() - Utils.dpToPx(7, context));
        PixelMap pixelMap = PixelMap.create(initializationOptions);

        Texture texture = new Texture(pixelMap);
        Canvas canvas = new Canvas(texture);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(new Color(Color.getIntColor(Utils.argb(rippleColor))));
        paint.setAlpha(0.3f);
        canvas.drawCircle(x, y, radius, paint);
        if (radius > getHeight() / rippleSize) {
            radius += rippleSpeed;
        }
        if (radius >= getWidth()) {
            x = -1;
            y = -1;
            radius = getHeight() / rippleSize;
            if (onClickListener != null && clickAfterRipple) {
                onClickListener.onClick(this);
            }
        }
        return texture.getPixelMap();
    }

    /**
     * Make a dark color to ripple effect
     *
     * @return 改变后的颜色值
     */
    protected String makePressColorString() {
        int colorInt;
        if (backgroundColor.length() == 7) {
            colorInt = Color.getIntColor(backgroundColor);
        } else {
            colorInt = Color.getIntColor(backgroundColor.substring(0, backgroundColor.length() - 2));
        }
        int r = (colorInt >> 16) & 0xFF;
        int g = (colorInt >> 8) & 0xFF;
        int b = (colorInt >> 0) & 0xFF;
        r = Math.max(r - 30, 0);
        g = Math.max(g - 30, 0);
        b = Math.max(b - 30, 0);
        StringBuilder builder =
                new StringBuilder("#")
                        .append(colorPrefix(Integer.toHexString(r)))
                        .append(colorPrefix(Integer.toHexString(g)))
                        .append(colorPrefix(Integer.toHexString(b)));
        return builder.toString();
    }

    private String colorPrefix(String string) {
        return string.length() > 1 ? string : "00";
    }

    @Override
    public void setClickedListener(ClickedListener listener) {
        onClickListener = listener;
    }

    // Set color of background
    public void setBackgroundColor(String color) {
        this.backgroundColor = color;
        if (isEnabled()) {
            beforeBackground = backgroundColor;
        }
        setBackground(ShapeUtil.createDrawable(Color.getIntColor(Utils.rgba(color))));
    }

    public void setRippleSpeed(float rippleSpeed) {
        this.rippleSpeed = rippleSpeed;
    }

    public float getRippleSpeed() {
        return this.rippleSpeed;
    }

    public void setText(String text) {
        textButton.setText(text);
    }

    public void setTextColor(Color color) {
        textButton.setTextColor(color);
    }

    public Text getTextView() {
        return textButton;
    }

    public String getText() {
        return textButton.getText();
    }
}
